from sqlalchemy import Column, Integer, String, Float, Text, ForeignKey, Enum, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base_class import Base
import enum

class PaymentStatus(enum.Enum):
    pending = "pending"           # 待支付
    processing = "processing"     # 处理中
    success = "success"           # 支付成功
    failed = "failed"             # 支付失败
    refunding = "refunding"       # 退款中
    refunded = "refunded"         # 已退款

class PaymentMethod(Base):
    __tablename__ = "payment_methods"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)  # 支付方式名称
    code = Column(String(50), unique=True)      # 支付方式代码
    description = Column(Text)
    is_active = Column(Boolean, default=True)
    config = Column(Text)  # JSON格式存储支付配置信息

class Payment(Base):
    __tablename__ = "payments"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    payment_method_id = Column(Integer, ForeignKey("payment_methods.id"))
    amount = Column(Float, nullable=False)
    status = Column(Enum(PaymentStatus), default=PaymentStatus.pending)
    transaction_id = Column(String(100))  # 支付平台交易号
    payment_time = Column(DateTime)       # 支付时间
    callback_data = Column(Text)          # 支付回调数据
    error_message = Column(String(255))   # 错误信息

    # 关联
    order = relationship("Order")
    payment_method = relationship("PaymentMethod")

class Refund(Base):
    __tablename__ = "refunds"

    id = Column(Integer, primary_key=True, index=True)
    payment_id = Column(Integer, ForeignKey("payments.id"))
    amount = Column(Float, nullable=False)
    reason = Column(String(255))
    status = Column(Enum(PaymentStatus), default=PaymentStatus.refunding)
    refund_time = Column(DateTime)
    transaction_id = Column(String(100))  # 退款交易号
    callback_data = Column(Text)          # 退款回调数据
    error_message = Column(String(255))   # 错误信息

    # 关联
    payment = relationship("Payment")